<?php
class ModelSaleMail extends Model {

	public function addMail($data) {
		$data['date_added'] = $GLOBALS['V5_NOW'];
		$data['date_modified'] = $GLOBALS['V5_NOW'];
		return $this->db->insert('mail', $data);

	}

	public function editMail($mail_id, $data) {
		$data['date_modified'] = $GLOBALS['V5_NOW'];
		return $this->db->update('mail', $data, "mail_id = $mail_id");
	}

	public function getMail($mail_id) {
		return $this->db->queryOne("SELECT * FROM @@mail WHERE mail_id = $mail_id");
	}

	public function deleteMail($mail_id) {
		if (is_array($mail_id)) $mail_id = implode(',', $mail_id);
		$this->db->runSql("DELETE FROM @@mail WHERE mail_id IN ($mail_id)");
	}

	public function getMails($filter = null) {
		$sql = "SELECT * FROM @@mail WHERE 1";
		if ($filter) {
			if ($filter->get('filter_subject')) {
				$sql .= " AND subject LIKE '%" . ES($filter->get('filter_subject')) . "%'";
			}
			$sql .= $filter->sort('mail_id', 'DESC');
			$sql .= $filter->limit();
		}

		$query = $this->db->query($sql);
		return $query->rows;
	}

	public function getTotalMails($filter = null) {
		$sql = "SELECT COUNT(*) AS total FROM @@mail WHERE 1";
		if ($filter) {
			if ($filter->get('filter_subject')) {
				$sql .= " AND subject LIKE '%" . ES($filter->get('filter_subject')) . "%'";
			}
		}
		return $this->db->queryOne($sql);
	}
}